﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Medianamik.Core.Querying;

namespace Medianamik.Core.DAL.SQL
{
    public class PagedQuery : ISqlQueryPart 
    {
        public RowNumberQuery InnerQuery
        {
            get; private set;
        }
        public int SkipCount
        {
            get; private set;
        }
        public int TakeCount
        {
            get; private set;
        }

        public PagedQuery(RowNumberQuery pInnerQuery,int pSkipCount, int pTakeCount )
        {
            InnerQuery = pInnerQuery;
            SkipCount = pSkipCount;
            TakeCount = pTakeCount;
        }

        #region ISqlQueryPart Members

        public StringBuilder ToSQL()
        {

            var q = new StringBuilder(" SELECT ");
            q.Append("t.rownum ");
            foreach (var c in InnerQuery.SelectClause.Columns)
            {
                q.Append(", t." + c.Name);
              
            }
            q.Append(" FROM ( ")
                .Append(InnerQuery.ToSQL())
                .Append(" ) as t ");

            var where = new WhereClause()
                .AddPredicate(new Predicate("t.rownum", Comparison.MoreThan, new NumericExpression(SkipCount)))
                .AddPredicate(new Predicate("t.rownum", Comparison.LessThanOrEqual,new NumericExpression(SkipCount + TakeCount)));

            q.Append(where.ToSQL());

            return q;
        }

        #endregion
    }
}
